import {Component, useEffect} from "react"
import {
    Button,
    Form,
    Input,
    Table,
    message,
    Spin,
    Modal,
} from 'antd';
import {ExclamationCircleOutlined} from '@ant-design/icons'
import Crud from "../../utils/crud"
import {getFormData} from "../../utils"
import {crudColumns, crudRequest} from '../../assets/js/tableOptions'
import "./index.scss"
import {store} from "../../store"
import {updateTableData} from "../../store/crudReducer.js"

const MyForm = (props) => {
    const [form] = Form.useForm();
    useEffect(() => {
        form.setFieldsValue({})
    })
    const search = () => {
        let data = getFormData(form.getFieldsValue())
        if (Object.values(data).some(key => key !== "" && key !== null && key !== undefined)) {
            let arr = filterData(data)
            if (!arr.length > 0) return props.getTable();
            props.updateTable(arr)
            store.dispatch(updateTableData(arr))
        } else {
            message.warning('请输入查询条件');
        }
    }
    const filterData = (data) => {
        let {tableData} = store.getState().crud
        let arr = []
        let values = Object.values(data)
        let keys = Object.keys(data)
        const createFilter = (str, key) => {
            return (filterItem) => {
                return (filterItem[key].toLowerCase().indexOf(str.toLowerCase()) === 0);
            };
        }
        if (values.length > 0) {
            let a
            // arr=tableData.filter(createFilter(values[0],'name'))
            values.forEach((item, i) => {
                console.log('--->values[i]',values)
                console.log('--->keys[i]', keys[i])
                // a = tableData.filter(createFilter(values[i], keys[i]))
                // arr.push(a)
            })
        }
        return arr
    }
    const reset = () => {
        form.resetFields()
        props.getTable()
    }
    return (
        <Form form={form}
              name="basic"
              layout="inline"
              colon={false}
        >
            <Form.Item label="姓名" name="name">
                <Input placeholder="请输入姓名" allowClear/>
            </Form.Item>
            <Form.Item label="地址" name="address">
                <Input placeholder="请输入地址" allowClear/>
            </Form.Item>
            <Form.Item>
                <Button type="primary" onClick={search}>查询</Button>
            </Form.Item>
            <Form.Item>
                <Button onClick={reset}>重置</Button>
            </Form.Item>
        </Form>
    )
}
export default class Index extends Component {
    state = {
        myCrud: {},
        loading: false,
        pagination: {
            current: 1,
            pageSize: 20,
        },
        tableData: [],
        columns: crudColumns(this)
    }

    componentDidMount () {
        let props = crudRequest()
        this.setState({myCrud: new Crud(props)}, () => {
            this.getTable()
        })
    }

    getTable = () => {
        this.setState({loading: true})
        this.state.myCrud.getTable().then(res => {
            this.setState({tableData: res});
            store.dispatch(updateTableData(res))
            this.setState({loading: false})
        })
    }
    updateTable = (data) => {
        this.setState({tableData: data});
    }
    removeCell = (row) => {
        let {name} = row;
        let _this = this
        return () => {
            Modal.confirm({
                title: `Do you Want to delete ${name}`,
                icon: <ExclamationCircleOutlined/>,
                onOk () {
                    let {tableData} = store.getState().crud;
                    let data = tableData.filter(item => item.id !== row.id)
                    store.dispatch(updateTableData(data))
                    _this.setState({})
                    message.success('删除成功')
                }
            });

        }
    }
    changeCurrent = (current, pageSize) => {
        this.setState({pagination: {current: current, pageSize: pageSize}})
    }

    render () {
        const {columns, pagination, loading} = this.state;
        let {tableData} = store.getState().crud;
        return (
            <div>
                <div className="form-box">
                    <MyForm updateTable={this.updateTable} getTable={this.getTable}/>
                </div>
                <div className="table-box">
                    <Spin spinning={loading} delay={500}>
                        <Table
                            rowKey='id'
                            columns={columns}
                            dataSource={tableData}
                            pagination={{
                                ...pagination,
                                total: tableData.length,
                                showTotal:(total) => `共计： ${total}条`,
                                onChange: this.changeCurrent
                            }}
                            scroll={{y: 590,}}
                        >
                        </Table>
                    </Spin>
                </div>
            </div>
        );
    }
}
